using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFTemplateLib.Controls
{
	/// <summary>
	/// 可翻转的内容控件
	/// </summary>
	public class FlipableContentControl : ContentControl
	{
		private readonly object _lockObj = new object();

		static FlipableContentControl()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(FlipableContentControl), new FrameworkPropertyMetadata(typeof(FlipableContentControl)));
		}

		#region [依赖属性] 翻转类型（水平或垂直）
		/// <summary>
		/// [依赖属性] 翻转类型（水平或垂直，默认水平）
		/// </summary>
		public Orientation FlipType
		{
			get => (Orientation)GetValue(FlipTypeProperty);
			set => SetValue(FlipTypeProperty, value);
		}
		public static readonly DependencyProperty FlipTypeProperty =
			DependencyProperty.Register(nameof(FlipType), typeof(Orientation), typeof(FlipableContentControl), new PropertyMetadata(Orientation.Horizontal, OnFlipTypeChanged));
		#endregion

		#region [依赖属性] 是否翻转
		/// <summary>
		/// 是否翻转
		/// </summary>
		public bool IsFlip
		{
			get => (bool)GetValue(IsFlipProperty);
			set => SetValue(IsFlipProperty, value);
		}
		/// <summary>
		/// [依赖属性] 是否翻转
		/// </summary>
		public static readonly DependencyProperty IsFlipProperty =
			 DependencyProperty.Register(nameof(IsFlip), typeof(bool), typeof(FlipableContentControl), new PropertyMetadata(false, ChangedFlipStatus));
		#endregion

		#region 方法

		/// <summary>
		/// 翻转类型改变
		/// </summary>
		private static void OnFlipTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var control = d as FlipableContentControl;
			if(control == null)
				return;

			lock(control._lockObj)
			{
				//只有被设置为翻转状态时才需要处理;
				if(control.IsFlip)
				{
					//从垂直翻转变为水平翻转;
					if(control.FlipType == Orientation.Horizontal)
					{
						control.LayoutTransform = new ScaleTransform(-1, 1);
					}
					else
					{
						control.LayoutTransform = new ScaleTransform(1, -1);
					}
				}
			}
		}

		/// <summary>
		/// 改变翻转状态
		/// </summary>
		private static void ChangedFlipStatus(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var control = d as FlipableContentControl;
			if(control == null)
				return;

			lock(control._lockObj)
			{
				//变为需要翻转;
				if(control.IsFlip)
				{
					//翻转类型为水平翻转;
					if(control.FlipType == Orientation.Horizontal)
					{
						control.LayoutTransform = new ScaleTransform(-1, 1);
					}
					else
					{
						control.LayoutTransform = new ScaleTransform(1, -1);
					}
				}
				else
				{
					control.LayoutTransform = new ScaleTransform(1, 1);
				}
			}
		}

		#endregion
	}
}
